Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Race Condition in Axios Interceptor for Refresh Token #356

Merged
merged 4 commits into from
Sep 23, 2024

Conversation

devleejb
Copy link
Member

@devleejb devleejb commented Sep 23, 2024

What this PR does / why we need it:
This PR addresses a race condition in the implementation of the Axios interceptor for refreshing access tokens. Recently, a refresh token mechanism was introduced, which can issue new access tokens via the Axios interceptor. However, the interceptor logic resides within a useEffect hook, leading to scenarios where Axios calls may be triggered before the interceptor is fully set up. This can result in unauthorized requests being sent with expired tokens.

To resolve this issue, the Axios interceptor will be configured before any calls are made, ensuring that all requests utilize a fresh access token.

Which issue(s) this PR fixes:

Fixes #

Special notes for your reviewer:

Does this PR introduce a user-facing change?:


Additional documentation:


Checklist:

  • Added relevant tests or not required
  • Didn't break anything

Summary by CodeRabbit

  • New Features

    • Introduced an Axios response interceptor to manage 401 errors and token refresh logic.
    • Enhanced user authentication flow by automatically retrying requests after refreshing tokens.
    • Updated loading state representation in the authentication context with new isPending status.
  • Bug Fixes

    • Removed outdated authentication handling logic from the main app component for improved clarity and performance.

Copy link
Contributor

coderabbitai bot commented Sep 23, 2024

Walkthrough

The changes involve the removal of authentication handling logic from the frontend/src/App.tsx file, specifically eliminating the useDispatch hook and the associated token refresh and user logout functionality. In contrast, the frontend/src/hooks/api/user.ts file introduces a new state variable to manage an Axios response interceptor for handling 401 errors, allowing for token refresh attempts and user logout when necessary. Additionally, the AuthProvider.tsx file has been updated to reflect changes in the user query logic.

Changes

File Change Summary
frontend/src/App.tsx Removed useDispatch hook and related logic for token refresh and user logout, simplifying the component.
frontend/src/hooks/api/user.ts Added axiosInterceptorAdded state variable to manage an Axios interceptor for handling 401 errors and token refresh logic.
frontend/src/providers/AuthProvider.tsx Updated user query logic to include isPending state, altering how loading states are represented in the context.

Possibly related PRs

Suggested labels

enhancement 🌟

Poem

In the meadow, bright and free,
Changes hop like bunnies, you see!
With tokens fresh and logic light,
Our app now dances in delight.
No more dispatches, just a breeze,
Hopping forward with such ease! 🐇✨


Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 81cf8c8 and 7e27671.

Files selected for processing (2)
  • frontend/src/hooks/api/user.ts (2 hunks)
  • frontend/src/providers/AuthProvider.tsx (1 hunks)
Files skipped from review as they are similar to previous changes (2)
  • frontend/src/hooks/api/user.ts
  • frontend/src/providers/AuthProvider.tsx

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    -- I pushed a fix in commit <commit_id>, please review it.
    -- Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    -- @coderabbitai generate unit testing code for this file.
    -- @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    -- @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    -- @coderabbitai read src/utils.ts and generate unit testing code.
    -- @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    -- @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Outside diff range and nitpick comments (1)
frontend/src/App.tsx (1)

Line range hint 1-124: Summary: Changes align with PR objectives, but comprehensive testing is crucial.

The modifications to the App component, including the removal of Redux-related logic and the token refresh mechanism, align well with the PR objectives of fixing the race condition in the Axios interceptor for refresh token. These changes should help prevent unauthorized requests due to expired tokens.

However, to ensure the overall functionality and security of the application, please consider the following:

  1. Thoroughly test the new token refresh implementation to verify its effectiveness and reliability.
  2. Conduct end-to-end testing of the authentication flow to ensure seamless user experience.
  3. Verify that all parts of the application that relied on the previous Redux-based token refresh mechanism have been updated accordingly.
  4. Review and update any relevant documentation to reflect these architectural changes.

Consider documenting the new token refresh mechanism and updating any relevant architecture diagrams to reflect these changes. This will help maintain clear communication about the application's authentication flow for future development and maintenance.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 5913e92 and d2c615f.

Files selected for processing (2)
  • frontend/src/App.tsx (1 hunks)
  • frontend/src/hooks/api/user.ts (2 hunks)
Additional comments not posted (4)
frontend/src/App.tsx (3)

10-10: LGTM: Import changes align with PR objectives.

The removal of the useDispatch import is consistent with the PR's goal of removing the Redux-based token refresh logic from the App component.


Line range hint 86-92: Verify 401 error handling in queryClient setup.

The error handling logic in the queryClient setup has been retained, which is good for maintaining the application's robustness. However, given the changes to the token refresh mechanism, it's important to verify if the current 401 error handling is still appropriate.

Please review the 401 error handling logic to ensure it aligns with the new token refresh implementation.

To assist in verifying the 401 error handling, please run the following script:

#!/bin/bash
# Description: Search for 401 error handling implementations

echo "Searching for 401 error handling logic:"
rg --type typescript --type javascript '(401|unauthorized)' -g '!{test,spec,__tests__}/**'

echo "\nSearching for refresh token logic:"
rg --type typescript --type javascript '(refresh.*token|token.*refresh)' -g '!{test,spec,__tests__}/**'

This script will help identify where 401 error handling and refresh token logic are implemented throughout the application. Please review the results to ensure that 401 errors are handled appropriately in conjunction with the new token refresh mechanism.


Line range hint 52-124: Approve removal of Redux logic, but verify new token refresh implementation.

The removal of Redux-related logic and the useEffect hook for token refresh from the App component aligns with the PR objectives. This change addresses the potential race condition where Axios calls could be made before the interceptor was fully configured.

However, it's crucial to ensure that the token refresh functionality has been implemented elsewhere in the application to maintain proper authentication flow.

To verify the new token refresh implementation, please run the following script:

This script will help identify where the new token refresh logic might have been implemented. Please review the results to ensure that the token refresh functionality is properly handled in the application.

Verification successful

Verified removal of Redux logic and confirmed token refresh implementation exists elsewhere.

The token refresh functionality is properly implemented in the following files:

  • frontend/src/hooks/api/user.ts
  • frontend/src/store/authSlice.ts
  • backend/src/auth/auth.service.ts
  • backend/src/auth/jwt-refresh.strategy.ts
  • frontend/src/pages/auth/callback/Index.tsx

All necessary authentication flows are maintained, and the removal of Redux-related logic from the App component does not impact the application's functionality.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for new token refresh implementation

# Look for files that might contain the new token refresh logic
echo "Searching for potential token refresh implementations:"
rg --type typescript --type javascript -i '(refresh.*token|token.*refresh)' -g '!{test,spec,__tests__}/**'

# Look for Axios interceptor setups
echo "\nSearching for Axios interceptor setups:"
rg --type typescript --type javascript 'axios\.interceptors\.(request|response)\.use' -g '!{test,spec,__tests__}/**'

Length of output: 534


Script:

#!/bin/bash
# Description: Search for new token refresh implementation and Axios interceptors

echo "Searching for potential token refresh implementations:"
rg --glob "!{test,spec,__tests__}/**" -i "(refresh.*token|token.*refresh)" --type-add 'ts=*.ts' --type-add 'tsx=*.tsx' --type ts --type tsx

echo -e "\nSearching for Axios interceptor setups:"
rg --glob "!{test,spec,__tests__}/**" "axios\.interceptors\.(request|response)\.use" --type-add 'ts=*.ts' --type-add 'tsx=*.tsx' --type ts --type tsx

Length of output: 627


Script:

#!/bin/bash
# Description: Search for new token refresh implementation and Axios interceptors

echo "Searching for potential token refresh implementations:"
rg --glob "!{test,spec,__tests__}/**" -i "(refresh.*token|token.*refresh)" --type-add 'ts:*.ts' --type-add 'tsx:*.tsx' --type ts --type tsx

echo -e "\nSearching for Axios interceptor setups:"
rg --glob "!{test,spec,__tests__}/**" "axios\.interceptors\.(request|response)\.use" --type-add 'ts:*.ts' --type-add 'tsx:*.tsx' --type ts --type tsx

Length of output: 4788

frontend/src/hooks/api/user.ts (1)

52-52: Logic for enabling the query is appropriate.

The enabled condition Boolean(axiosInterceptorAdded && authStore.accessToken) ensures the query runs only when the interceptor is set up and an access token is available, preventing unauthorized requests.

frontend/src/hooks/api/user.ts Outdated Show resolved Hide resolved
frontend/src/hooks/api/user.ts Show resolved Hide resolved
frontend/src/hooks/api/user.ts Outdated Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Outside diff range and nitpick comments (2)
frontend/src/providers/AuthProvider.tsx (2)

12-12: LGTM! Consider adding a comment for clarity.

The addition of isPending to the destructured object from useGetUserQuery is a good improvement. It provides a more granular representation of the query status, which can help address the race condition mentioned in the PR objectives.

Consider adding a brief comment explaining the difference between isPending and isLoading for future maintainers:

// isPending: true when the query is initialized but hasn't started loading
// isLoading: true when the query is actively fetching data
const { data: user, isSuccess, isLoading, isPending } = useGetUserQuery();

Line range hint 1-24: Overall, great job addressing the race condition!

The changes made to this file effectively tackle the race condition issue described in the PR objectives. The addition of isPending and its incorporation into the loading state logic should prevent premature API calls and ensure that the Axios interceptor is properly set up before any requests are made.

As a minor suggestion for future improvements, consider adding error handling to the useGetUserQuery hook:

const { data: user, isSuccess, isLoading, isPending, error } = useGetUserQuery();

// ... existing code ...

return (
  <AuthContext.Provider value={{ 
    isLoggedIn: isSuccess, 
    isLoading: isPending || isLoading,
    error: error ? error.message : null 
  }}>
    {/* ... existing code ... */}
  </AuthContext.Provider>
);

This addition would allow consumers of the AuthContext to handle potential errors in the user query, improving the overall robustness of the authentication system.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between d2c615f and 81cf8c8.

Files selected for processing (1)
  • frontend/src/providers/AuthProvider.tsx (1 hunks)

frontend/src/providers/AuthProvider.tsx Outdated Show resolved Hide resolved
@devleejb devleejb self-assigned this Sep 23, 2024
@devleejb devleejb merged commit 6495c6f into main Sep 23, 2024
2 checks passed
@devleejb devleejb deleted the fix-refresh-token-race branch September 23, 2024 07:28
minai621 pushed a commit that referenced this pull request Nov 5, 2024
* Fix refresh token race condition

* Change the login loading condition

* Improve variable readability

* Fix typo
@coderabbitai coderabbitai bot mentioned this pull request Nov 8, 2024
2 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: Done
Development

Successfully merging this pull request may close these issues.

1 participant